package mail.gui;

import crypt.SignHandler;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import mail.util.Sender;

/**
 * Frame used for sending a single mail.
 *
 * @author Jonas.Lindmark
 */
public class MailSendFrame extends JInternalFrame implements ActionListener{
    private JTextField fields[] = new JTextField[3];
    private JTextArea msg = new JTextArea();
    public MailSendFrame()
    {
        super("Send new mail",true,true,true,true);
        //lots of graphical stuff
        setSize(300,300);
        setLayout(new BorderLayout());
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        JPanel top = new JPanel();
        add(top,BorderLayout.NORTH);
        top.setLayout(new GridLayout(4,2));
        JLabel label = new JLabel("From:");
        fields[0] = new JTextField("your addres...");
        top.add(label);top.add(fields[0]);
        label = new JLabel("To:");
        fields[1] = new JTextField("reciever address...");
        top.add(label);top.add(fields[1]);
        label = new JLabel("Subject");
        fields[2] = new JTextField("");
        top.add(label);top.add(fields[2]);



        label = new JLabel("Message:");
        msg.setSize(300,200);
        JPanel bot = new JPanel();
        bot.setLayout(new BorderLayout());
        bot.add(label,BorderLayout.WEST);
        JScrollPane scrollPane = new JScrollPane(msg);
        bot.add(scrollPane,BorderLayout.CENTER);
        add(bot,BorderLayout.CENTER);

        JButton button = new JButton("Send");
        button.addActionListener(this);
        button.setActionCommand("send");
        add(button,BorderLayout.SOUTH);
        button = new JButton("sign");
        button.addActionListener(this);
        button.setActionCommand("sign");
        add(button,BorderLayout.WEST);
        pack();
    }
    //handle actions
    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("sign"))
        {
            signMail();
        } else if(e.getActionCommand().equals("send"))
        {
            sendMailNow();
        }
    }
    /**
     * Signs the current email. Will ignore leading and trailing
     * white-space of the body. Will also remove previously existing
     * signatures if such exists.
     */
    private void signMail()
    {
        String message = msg.getText();
        if (message == null || message.trim().equals(""))
            return;
        String privFile = null;
        while (privFile == null)
        {

            privFile = JOptionPane.showInputDialog("Please enter name of the private key file");
            if (privFile != null)
            {
                File f = new File(privFile);
                if (!f.exists())
                {
                    JOptionPane.showMessageDialog(null, "File not found.");
                    privFile = null;
                } else {
                    break;
                }
            }
        }
        message = message.trim();
        String str = new SignHandler().sign(message, privFile);
        String text = removeSign(msg.getText());
        msg.setText(text+"<simplesign>"+str+"</simplesign>\n");
    }
    /**
     * Attempts to send the current mail.
     */
    private void sendMailNow()
    {
        for(int i=0; i<fields.length; i++)
        {
            if (fields[i] == null || fields[i].getText().equals(""))
            {
                JOptionPane.showMessageDialog(null, "You have to enter text in all fields.");
                return;
            }
        }
        if (msg.getText() == null || msg.getText().equals(""))
        {
            JOptionPane.showMessageDialog(null, "You have to enter text in all fields");
            return;
        }
        Sender s = new Sender();
        try {
            s.setSender(fields[0].getText());
        } catch (Exception ex) {
            System.out.println(new Date().toString() + " : ERROR : Invalid sender: " + fields[0].getText());
            JOptionPane.showMessageDialog(null, "Invalid sender");
            return;
        }

        final String to = fields[1].getText();
        final String subj = fields[2].getText();
        final String body = msg.getText();
        try{
            s.sendMail(to, subj, body);
            dispose();
        } catch(Exception ex) {
            System.out.println(new Date().toString() + " : ERROR : Failed to send to: " + to);
            JOptionPane.showMessageDialog(null, "Failed to send.");
            ex.printStackTrace();
        }
    }
    /**
     * Remove all signatures from the input String and returns
     * the _cleaned_ String.
     *
     * @param text The String possibly containing multiple signatures
     * @return The original String stripped of signatures.
     */
    private String removeSign(String text)
    {
        return text.replaceAll("<simplesign>(.*)</simplesign>","");
    }
}
